// utils/request.js
import axios from 'axios';

// 创建 axios 实例
const service = axios.create({
    baseURL: 'https://your-api-base-url.com', // 设置请求的基础 URL，根据实际情况修改
    timeout: 5000 // 请求超时时间，单位为毫秒
});

// 请求拦截器
service.interceptors.request.use(
    config => {
        const token = uni.getStorageSync('token');
        if (token) {
            config.headers['Authorization'] = `Bearer ${token}`;
        }
        return config;
    },
    error => {
        console.log(error);
        return Promise.reject(error);
    }
);

// 响应拦截器
service.interceptors.response.use(
    response => {
        const res = response.data;
        if (res.code !== 200) {
            uni.showToast({
                title: res.message || '请求出错',
                icon: 'none'
            });
            return Promise.reject(new Error(res.message || 'Error'));
        } else {
            return res;
        }
    },
    error => {
        console.log('err' + error);
        uni.showToast({
            title: error.message,
            icon: 'none'
        });
        return Promise.reject(error);
    }
);

// 封装常用的请求方法
const get = (url, params = {}) => {
    return service.get(url, { params });
};

const post = (url, data = {}) => {
    return service.post(url, data);
};

const put = (url, data = {}) => {
    return service.put(url, data);
};

const del = (url, params = {}) => {
    return service.delete(url, { params });
};

export { get, post, put, del };